<?php

namespace app\model;

use app\stateData;
use think\db\Query;
use think\facade\Db;
use think\Model;
use think\model\concern\SoftDelete;

class OrderEnterpriseCertificateRegister extends Model
{
    /**
     * 企业库 证书注册
     */
    use SoftDelete;

    protected $deleteTime = 'delete_date';
    protected $createTime = 'create_date';

    public const GS_STATUS = [
        1 => '待匹配',
        2 => '排队中',
        3 => '已退回'
    ];
    //排队中
    public const GS_STATUS_TWO = 2;
    //已退回
    public const GS_STATUS_THREE = 3;

    public function getCertificateIdAttr($name): array
    {
        if (empty($name)) return [];
        return array_map ('intval', explode (',', $name));
    }

    public function getStatusAttr($name): array
    {
        return [
            'id' => $name,
            'text' => stateData::$_enter_certificate_reg[$name]
        ];
    }

    public function getProjectAttr($value): array
    {
        if ($value === '') {
            return [
                'id' => '',
                'text' => ''
            ];
        }
        return [
            'id' => (int)$value,
            'text' => stateData::$_project[$value]
        ];
    }

    public function getCertificateBAttr($value): array
    {
        if ($value === '') {
            return [
                'id' => '',
                'text' => ''
            ];
        }
        return [
            'id' => (int)$value,
            'text' => stateData::$_b_doc[$value]
        ];
    }

    public function getSocialSecurityAttr($value): array
    {
        if ($value === '') {
            return [
                'id' => '',
                'text' => ''
            ];
        }

        return [
            'id' => (int)$value,
            'text' => stateData::$_social_security[$value]
        ];
    }

    public function getCycleAttr($value): array
    {
        if ($value === '' || $value == 0) {
            return [
                'id' => '',
                'text' => ''
            ];
        }
        return [
            'id' => (int)$value,
            'text' => stateData::$_cycle[$value]
        ];

    }

    public function getTransferAttr($value): array
    {
        $values = $value ?: '';
        return [
            'id' => $values,
            'text' => stateData::$_transfer[$value]
        ];
    }

    public function getOutOrgAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new UserOrganization)->getStructureName ($name) ?: ''
        ];
    }

    public function getBusinessIdAttr($name)
    {
        return [
            'id' => $name,
            'text' => (new SystemBusiness)->getBusinessIdTitle ($name) ?: ''
        ];

    }

    public function getOutUidAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new User)->getIdNickName ($name) ?: ''
        ];
    }

    public function getNoticeIdAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new User)->getIdNickName ($name) ?: ''
        ];
    }

    public function getSaleOrgAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new UserOrganization)->getStructureName ($name) ?: ''
        ];
    }

    public function getSaleUidAttr($name): array
    {
        return [
            'id' => $name ?: '',
            'text' => (new User)->getIdNickName ($name) ?: ''
        ];
    }

    public function getGetOrgAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new UserOrganization)->getStructureName ($name) ?: ''
        ];
    }

    public function getGetUidAttr($name): array
    {
        return [
            'id' => $name,
            'text' => (new User)->getIdNickName ($name) ?: ''
        ];
    }


    //公示电子证书文件
    public function getElectronicCertificateFileAttr($value)
    {
        if (!empty($value)) {
            $value = str_replace ('\\', '/', 'http://' . $_SERVER['HTTP_HOST'] . '/storage/' . $value);
        }
        return $value;
    }

    //B证电子证书文件
    public function getBElectronicCertificateFileAttr($value)
    {
        if (!empty($value)) {
            $value = str_replace ('\\', '/', 'http://' . $_SERVER['HTTP_HOST'] . '/storage/' . $value);
        }

        return $value;
    }

    public function getBRegElectronicCertificateDateAttr($name)
    {
        if ($name === '0000-00-00 00:00:00') return "";
        return $name;
    }

    public function getBElectronicCertificateDateAttr($name)
    {
        if ($name === '0000-00-00 00:00:00') return "";
        return $name;
    }

    public function getElectronicCertificateDateAttr($name)
    {
        if ($name === '0000-00-00 00:00:00') return "";
        return $name;
    }

    public function getCertificateLeixingAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return (new SystemCertificate)->getWhereIdCertificateModel ($name) ?: '';
//        return [
//            'id'=>$name,
//            'text'=>(new SystemCertificate)->getWhereIdCertificateModel ($name)?:''
//        ];
    }

    public function getCertificateLeibieAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return (new SystemCertificate)->getWhereIdCertificateModel ($name) ?: '';

    }

    public function getCertificateDengjiAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return (new SystemCertificate)->getWhereIdCertificateModel ($name) ?: '';
//        return [
//            'id'=>$name,
//            'text'=>(new SystemCertificate)->getWhereIdCertificateModel ($name)?:''
//        ];
    }

    public function getCertificateZhuanyeAttr($name)
    {
        if ($name == 0) {
            return "";
        }
        return (new SystemCertificate)->getWhereIdCertificateModel ($name) ?: '';
//        return [
//            'id'=>$name,
//            'text'=>(new SystemCertificate)->getWhereIdCertificateModel ($name)?:''
//        ];
    }

    public function getSfkStatusAttr($name)
    {
        return [
            'id' => $name ?: '',
            'text' => stateData::$_sfk_status[$name]
        ];
    }

//    public function getPriceUnitAttr($name)
//    {
//        if ($name == '0.00') {
//            return '';
//        }
//        return $name;
//    }

    public function getGzStatusAttr($name)
    {
        return [
            'id' => $name ?: '',
            'text' => self::GS_STATUS[$name]
        ];
    }


    //一对多关联
    public function business()
    {
        return $this->hasOne (SystemBusiness::class, 'id', 'business_id')->bind (['business_name', 'business_name']);
    }

    //获取补充资料文件
//    public function supCompany()
//    {
//        return $this->hasMany (OrderEnterpriseCompany::class,'enter_id','id')->bind (['responsibility_uid'=>'responsibility_uid']);
//    }

    public function addRegCertificateModel($data)
    {
        return self::create ($data);
    }

    /**
     * 批量type查询
     * @param $typeIn
     * @return \app\model\OrderEnterpriseCertificateRegister[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRegCerTypeListModel($typeIn, $pageNum, $page = 1)
    {
        return $this->whereIn ('type', $typeIn)
//            ->fetchSql(true)
            ->where ('people_num', '>', 0)
//            ->where ('gz_status', '<>', self::GS_STATUS_THREE)
            ->where ('gz_status', '<>', self::GS_STATUS_THREE)
            ->order ('create_date ASC')
            ->select ()
            ->toArray ();
    }

    public function getRegCerTypeCountModel($typeIn): int
    {
        return $this->whereIn ('type', $typeIn)->count ();
    }


    //个人
    public function getThatPersonRegCerTypeListModel($typeIn, $id, $pageNum, $page = 1)
    {

//        $data = Db::query(
//            "select * from order_enterprise_certificate_register r left join order_enterprise_company c on r.certificate_code = c.certificate_code WHERE r.get_uid = '".$id."'and r.type in('".$typeIn."')
//            union ALL
//            select
//            *
//              from order_enterprise_certificate_register r inner join order_enterprise_company c on r.certificate_code = c.certificate_code WHERE c.responsibility_uid = ".$id
//        );
//        $data = Db::query("
//            select * from order_enterprise_certificate_register r left join order_enterprise_company c on r.certificate_code = c.certificate_code WHERE r.get_uid = '".$id."'and r.type in('".$typeIn."')
//
//            union ALL
//
//            select * from order_enterprise_certificate_register r inner join order_enterprise_company c on r.certificate_code = c.certificate_code WHERE c.responsibility_uid = ".$id);
//        $data = $this->with ('supCompany')->where (['get_uid'=>$id])->whereIn ('type',$typeIn) ->page($page,stateData::$_page)->select ();
//        return array_slice($data, ($page-1)*$pageNum, $pageNum);
        return $this->where (['get_uid' => $id])
            ->whereIn ('type', $typeIn)
            ->where ('people_num', '<>', 0)
            ->order ('create_date ASC')
            ->select ()
            ->toArray ();
    }

    public function getThatPersonRegCerTypeCountModel($typeIn, $id): int
    {
        return $this->where (['get_uid' => $id])->whereIn ('type', $typeIn)->count ();
    }

    /**************************************
     * 公示栏条件查询加分页
     * @param $where
     * @param $page
     * @return \app\model\OrderEnterpriseCertificateRegister[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPublicityListModel($where, $sort,$whereDate,$whereOr)
    {
        $db = $this->where ($where);
        if (!empty($whereOr)){
            $db->whereRaw ($whereOr);
        }
        if (!empty($whereDate)){
            $db->whereRaw ($whereDate);
        }
        return $db->fetchSql(false)->whereIn ('type', '2,3')->where ('dz_status', 0)->order ($sort)->select ()->toArray();

    }

    public function getPublicityCountModel($where)
    {
        return $this->where ($where)->whereIn ('type', '2,3')->count ();
    }

    /**
     * 根据id查询单条信息
     * @param $id
     * @return \app\model\OrderEnterpriseCertificateRegister|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getWhereIdDataModel($id)
    {

        $data = $this->where (['id' => $id])->findOrEmpty ();

        if (!$data->isEmpty ()) {
            return $data->toArray ();
        }
        return null;
    }

    /**
     * 通过id查询证书信息
     * @param $id
     * @return \app\model\OrderEnterpriseCertificateRegister|array|mixed|\think\Model
     */
    public function getIdDataModel($id)
    {
        $data = $this->where (['id' => $id])->findOrEmpty ();
        if (!$data->isEmpty ()) {
            return $data->toArray ();
        }
        return null;
    }

    /**
     * id删除
     * @param $id
     * @return bool
     */
    public function delIdData($id)
    {
        return self::destroy ($id);
    }

    public function getInvertedEvidenceListModel($range)
    {
        return $this->whereIn ('type', $range)->select ();
    }

    public function editDataModel($data): OrderEnterpriseCertificateRegister
    {
        return self::update ($data);
    }

    /**
     * 通过证书编号修改信息
     * @param $cer
     * @param $data
     * @return \app\model\OrderEnterpriseCertificateRegister
     */
    public function editWhereCerModel($cer,$data)
    {
        return $this->where (['certificate_code'=>$cer])->update ($data);
    }

    /**
     * 查询注册单位 | 聘用单位 等于where信息
     * @param $where
     * @return \app\model\OrderEnterpriseCertificateRegister|array|mixed|\think\Model
     */
    public function getWhereInfoModel($where)
    {

        $data = $this->where ("reg_unit|employ_unit_title", '=', $where)->findOrEmpty ();
        if (!$data->isEmpty ()) {
            return $data->toArray ();
        }
        return null;
    }

    /**
     * 完成订单操作
     * @param $id
     * @return \app\model\OrderEnterpriseCertificateRegister
     */
    public function completeOperateModel($id)
    {
        return $this->where (['id' => $id])->update (['status' => 1]);
    }

    /**
     * 修改订单为代成交
     * @param $id
     * @return \app\model\OrderEnterpriseCertificateRegister
     */
    public function saveStatusInitModel($id): OrderEnterpriseCertificateRegister
    {
        return $this->where (['id' => $id])->update (['status' => 0]);
    }

    /**
     * 通过提交id查询用户提交数据
     * @param $id
     * @return array
     */

    public function getUidSubmitIdModel($id): array
    {
        return $this->where (['get_uid' => $id])->column ('id');
    }

    public function getUidSubmitIdCountModel($id)
    {
        return $this->where (['get_uid' => $id])->count ();
    }

    /**
     * 补充公示资料
     * @param $id
     * @return \app\model\OrderEnterpriseCertificateRegister|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getsuppleInfo($id)
    {
        return $this->where (['id' => $id])->field ('
                electronic_certificate_illustrate,
                electronic_certificate_file,
                electronic_certificate_date,
                b_electronic_certificate_illustrate,
                b_electronic_certificate_file,
                b_electronic_certificate_date,
                b_reg_electronic_certificate_date
            ')->find ();
    }

    /**
     * 人数自减一
     * @param $id
     * @return void
     */
    public function peopleNumDecModel($id): void
    {
        $this->where (['id' => $id])->dec ('people_num')->update ();
    }

    /**
     * 人数自增一
     * @param $id
     * @return void
     */
    public function peopleNumIncModel($id): void
    {
        $this->where (['id' => $id])->inc ('people_num')->update ();
    }

    public function getCertificateCodeFindData($certificate): ?array
    {
        $data = $this->where (['certificate_code' => $certificate])->findOrEmpty ();
        if (!$data->isEmpty ()) {
            return $data->toArray ();
        }
        return null;
    }

    /**
     * 使用获取器获取数据
     * @param $field //获取器名字
     * @param $val //获取器值
     * @return mixed
     */
    public function gethqq($field, $val)
    {
        $fieldsCase = $this->toCamelCase ($field);
        if (method_exists (__CLASS__, $fieldsCase)) {

            return $this->$fieldsCase ($val);
        }
        return $val;

    }

    //下划线命名到驼峰命名
    public function toCamelCase($str)
    {
        $array = explode ('_', $str);
        $result = $array[0];
        $len = count ($array);
        if ($len > 1) {
            for ($i = 1; $i < $len; $i++) {
                $result .= ucfirst ($array[$i]);
            }
        }
        return $result;
    }

    /**
     * 通过身份证号码查询附属业务
     * @param $idCard
     * @return mixed
     */
    public function getIdCardAncillary($idCard)
    {
        return $this->where (['person_id_card' => $idCard])->value ('ancillary_businesses_id');
    }

    /**
     * 通过身份证查询人才信息
     * @param $idCard
     * @return array|null
     */
    public function getIdCardDataModel($idCard)
    {
        $data = $this->where (['person_id_card' => $idCard])->findOrEmpty ();
        if (!$data->isEmpty ()) {
            return $data->toArray ();
        }
        return null;
    }

    /**
     * 通过证书id查询补全资料
     * @param $id
     * @return array|null
     */
    public function getExcelInfoModel($cer): ?array
    {
        $data = $this->where (['certificate_code' => $cer])
            ->field ('sum(price_unit/people_num) as sale_price,reg_unit')
            ->findOrEmpty ();
        if (!$data->isEmpty ()) {
            return $data->toArray ();
        }
        return null;
    }

    /**
     * Ⅱ类业务占比 - 证书注册业务分类统计
     */
    public function getBusinessGroupDataModel()
    {
        return $this->where (['type' => 1])->field ('certificate_code,business_id,price_unit,people_num')->select ()->toArray ();
    }

    public function getEnterModel($enter_code)
    {
        return $this->where (['certificate_code' => $enter_code])->select ()->toArray ();
    }

    /**
     * 获取出证单位对应订单编号
     * @param $title
     * @return array
     */
    public function getRegUnitCerModel($title)
    {
        return $this->where (['reg_unit' => $title])->column ('certificate_code');
    }

    public function whereIdData($id)
    {
        return $this->whereIn ('id', $id)->select ()->toArray ();
    }


    /**
     * 查询审核人为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getSaleUidDataModel($id)
    {
        return $this->where (['sale_uid' => $id])->column ('id');
    }

    public function editSaleUidDataModel($idArr, $id, $org)
    {
        return $this->whereIn ('id', $idArr)->update (['sale_uid' => $id, 'sale_org' => $org]);
    }

    /**
     * 查询收证人员为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getGetUidDataModel($id)
    {
        return $this->where (['get_uid' => $id])->column ('id');
    }

    public function editGetUidDataModel($idArr, $id, $org)
    {
        return $this->whereIn ('id', $idArr)->update (['get_uid' => $id, 'get_org' => $org]);
    }

    /**
     * 查询发起人为当前id的信息id集
     * @param $id
     * @return array
     */
    public function getNoticeIdDataModel($id)
    {
        return $this->where (['notice_id' => $id])->column ('id');
    }

    public function editNoticeIdDataModel($idArr, $id)
    {
        return $this->whereIn ('id', $idArr)->update (['notice_id' => $id]);
    }

    public function getFUidFieldDataModel($uid)
    {
        return $this->where (['sale_uid' => $uid])->whereOr ('get_uid', $uid)->whereOr ('notice_id', $uid)->field ('id,certificate_code,person_id_card,person_name')->select ()->toArray ();
    }

    /**
     * 查询订单编号相关订单数量
     * @param $cer
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getCerOrderNumModel($cer): int
    {
        return $this->where (['certificate_code' => $cer])->count ();
    }

    /**
     * 查询用户订单编号相关订单数量
     * @param $cer
     * @param $uid
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getUidCerOrderNumModel($cer, $uid): int
    {
        return $this->where (['certificate_code' => $cer, 'get_uid' => $uid])->count ();
    }

    public function gsStatusEdit($id, $status)
    {
        return $this->whereIn ('id', $id)->update (['gz_status' => $status]);
    }

    /**
     * 获取制定条件证书编号
     * @param $where
     * @return array
     */
    public function getWhereModel($where)
    {

        return $this->whereRaw ($where)->column ('certificate_code');
    }

    public function getCerLeixingModel($cer)
    {
        return $this->where (['certificate_code' => $cer])->value ('certificate_leixing');
    }

    /**
     * 报表中心-公司证书-提成占比
     * @param $bid
     * @param $uid
     * @param string $startDate
     * @param string $endDate
     * @return float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getTcblModel($bid, $uid, string $startDate, string $endDate)
    {
        $orderEnterPriseComposerModel = new  OrderEnterpriseCompany();
        $orderDealModel = new OrderDeal();
//        $cerArr = $this->where (['business_id' => $bid])->whereIn ('type',[1,3])->column ('certificate_code');

        //通过需求寻找证书成交详情
        $data = $orderEnterPriseComposerModel->getEnterPriseDataModel ($bid);

        $performance = 0;
        if ($data) {
            foreach ($data as $datum) {
                //判断成交时间是否满足
                $dealData = $orderDealModel->getCerComIdDateDataModel ($datum['id'], $datum['certificate_code'], '', $startDate, $endDate);
                if ($dealData) {
//                    if (strtotime ($dealData['create_date']) >= strtotime ($startDate) && strtotime ($dealData['create_date']) <= strtotime ($endDate)) {
                        if ($datum['performance_uid']) {
                            $performanceUid = explode (',', $datum['performance_uid']);
                            $puidCount = count ($performanceUid);
                            foreach ($performanceUid as $value) {
                                if ($value == $uid) {
                                    $performance += $datum['performance'] / $puidCount;
                                }
                            }
                        }
//                    }
                }
            }
        }
        return $performance;
    }

    /**
     * 报表中心-倒证-提成占比
     * @param $bid
     * @param $uid
     * @param string $startDate
     * @param string $endDate
     * @return float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getDzTcblModel($bid, $uid, string $startDate, string $endDate)
    {
        $orderEnterPriseExchangeModel = new OrderEnterpriseExchange();
        $orderDealModel = new OrderDeal();
        $cerArr = $this->where (['business_id' => 0])->whereIn ('type',[2,3])->column ('certificate_code');

        //通过需求寻找证书成交详情
        $data = $orderEnterPriseExchangeModel->getEnterPriseDataModel ($cerArr, $startDate, $endDate);

        $performance = 0;
        if ($data) {
            foreach ($data as $datum) {
                //判断成交时间是否满足
                $dealData = $orderDealModel->getCerComIdDateDataModel ($datum['id'], $datum['certificate_code'], '', $startDate, $endDate);
                if ($dealData) {
//                    if (strtotime ($dealData['create_date']) >= strtotime ($startDate) && strtotime ($dealData['create_date']) <= strtotime ($endDate)) {
                        if ($datum['performance_uid']) {
                            $performanceUid = explode (',', $datum['performance_uid']);
                            $pUidCount = count ($performanceUid);
                            foreach ($performanceUid as $value) {
                                if ($value == $uid) {
                                    $performance += $datum['performance'] / $pUidCount;
                                }
                            }
                        }
//                    }
                }
            }
        }
        return $performance;
    }

    /**
     * 查询今日订单个数
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function getToDayCountFindModel():int
    {
        return  $this->whereDay('create_date')->count ();
    }
}